/**
 * __handler__:
 * 服务器系统内置的处理程序
 * User: ZhangXiao
 * Date: 14-4-23
 * Time: 下午5:37
 * File: sys/__handler__.js
 */
var url = require("url");
var util = require("util");
var path = require("path");
var fs = require("fs");

function handler_404(request, response, options) {
    response.writeHead(404, {
        "Content-Type": "text/html;charset=utf-8"
    });
    responseContent("404.html", request, response, options);

};

function handler_500(request, response, options) {
    response.writeHead(500, {
        "Content-Type": "text/html;charset=utf-8"
    });
    responseContent("500.html", request, response, options);
};

function responseContent(filename, request, response, options) {
    var filePath = path.resolve(options.approot, options.sys, filename);
    fs.exists(filePath, function (exist) {
        if (exist) {
            fs.readFile(filePath, "binary", function (err, data) {
                if (err) {

                } else {
                    response.write(data,"binary");
                    response.end();
                }
            });
        }
        else {
            var data = "<!DOCTYPE html><html><head><meta charset='utf-8'><script type='text/javascript'>window.location.href='/index';</script></head></html>";
            response.write(data);
            response.end();
        }
    });
}

exports.handlers = {
    "handler_500": handler_500,
    "handler_404": handler_404
};

